import java.io.*;

public class CopyDirectryandFiles {

	public static void main(String[] args) throws IOException {
		
		int a=0;
		
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the Source Directory to be Copied :");
		String sPath=br.readLine();
		
		File source=new File(sPath);
		
		
		System.out.println("Enter the path Where Destination Directory to be Copied :");
		String dPath=br.readLine();
		
		File destination=new File(dPath);
		
		if(!destination.exists())
		{
			destination.mkdir();
			
			copyDirectory(source, destination);
			
			a=1;
		}
		
		else
		{
			System.out.println("Destination directory already exist, Do you want to replace Now?");
	        String chkVal=br.readLine();
			
	        if(chkVal.equals("Y")||(chkVal.equals("y"))){
	        	copyDirectory(source, destination);

	        	a = 1;
	        }
	        else
	        {
	        	System.exit(0);
	        }
	    }
		
		if (a==1){
			
			System.out.println("File or directory moved successfully.");
		}
		else
		{
			System.exit(0);
		}
		
		
		
		
	}
	
	public static void copyDirectory(File sourceDir, File destDir) throws IOException{

	if(!destDir.exists()){

	destDir.mkdir();

	}

	File[] children = sourceDir.listFiles();

	for(File sourceChild : children){

	String name = sourceChild.getName();

	File destChild = new File(destDir, name);

	if(sourceChild.isDirectory()){

	copyDirectory(sourceChild, destChild);

	}

	else{

	copyFile(sourceChild, destChild);

	}

	}

	}
	
	
	
	public static void copyFile(File source, File dest) throws IOException{

		if(!dest.exists()){

		dest.createNewFile();

		}

		InputStream in = null;

		OutputStream out = null;

		try{

		in = new FileInputStream(source);

		out = new FileOutputStream(dest);

		byte[] buf = new byte[1024];

		int len;

		while((len = in.read(buf)) > 0){

		out.write(buf, 0, len);

		}

		}

		finally{

		in.close();

		out.close();

		}

		}
	
}
